extends KinematicBody2D

var maxSpeed = 25
var velocity = Vector2.ZERO
var direction = Vector2.RIGHT
var gravity = 500
export var isSpawning = true

var enenmyDeathScene = preload("res://scenes/EnemyDeath.tscn")

func _ready():
	$HitboxArea.connect("area_entered", self, "on_hitbox_entered")


func _process(delta):
	if (isSpawning):
		return
	velocity.x = (direction * maxSpeed).x

	if (not is_on_floor()):
		velocity.y += gravity * delta
	if ($FlipTimer.is_stopped() && 
	(!$Visuals/AnimatedSprite/RayCastBottom.is_colliding() or $Visuals/AnimatedSprite/RayCastBorder.is_colliding())):
		direction *= -1
		$FlipTimer.start()
	
	$Visuals/AnimatedSprite.scale.x = 1 if direction.x > 0 else -1
	
	move_and_slide(velocity, Vector2.UP)

func kill():
	var deathInstance = enenmyDeathScene.instance()
	if (velocity.x > 0):
		deathInstance.scale = Vector2(-1, 1)
	deathInstance.global_position = global_position
	get_parent().add_child(deathInstance)
	queue_free()
	
	
	
func on_hitbox_entered(_area2d):
	$"/root/Helpers".apply_camera_shake(1)
	kill()
